package com.itjin.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itjin.mapper.ExamHelperMapper;
import com.itjin.model.domain.entity.ExamHelper;
import com.itjin.model.domain.vo.AnxietyTipsVO;
import com.itjin.model.domain.vo.ExamHelperVO;
import com.itjin.model.domain.vo.PredictedPointVO;
import com.itjin.model.domain.vo.StudyPlanVO;
import com.itjin.model.request.StudyPlanRequest;
import com.itjin.model.request.WrongQuestionRequest;
import com.itjin.service.ExamHelperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 智能考试助手服务实现类
 */
@Service
@Slf4j
public class ExamHelperServiceImpl extends ServiceImpl<ExamHelperMapper, ExamHelper> implements ExamHelperService {

  @Autowired
  private RestTemplate restTemplate;

  // AI API配置参数
  private static final String SHISA_AI_API_URL = "https://openrouter.ai/api/v1/chat/completions";
  private static final String SHISA_AI_API_KEY = "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";
  private static final String SHISA_AI_MODEL = "shisa-ai/shisa-v2-llama3.3-70b:free";
  private static final String SITE_URL = "https://yourapplication.com";
  private static final String SITE_NAME = "User Center Application";

  /**
   * 调用AI接口
   * 添加更强的系统提示以获得更结构化的回复
   */
  private String callAiApi(String prompt) {
    try {
      // 设置请求头
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_JSON);
      headers.set("Authorization", "Bearer " + SHISA_AI_API_KEY);
      headers.set("HTTP-Referer", SITE_URL);
      headers.set("X-Title", SITE_NAME);

      // 构建请求体
      Map<String, Object> requestBody = new HashMap<>();
      requestBody.put("model", SHISA_AI_MODEL);

      List<Map<String, String>> messages = new ArrayList<>();

      // 更详细的系统提示，指导AI生成结构化的回复
      Map<String, String> systemMessage = new HashMap<>();
      systemMessage.put("role", "system");
      systemMessage.put("content",
          "你是一名专业的教育顾问与学习助手，擅长提供学习建议和规划。请提供清晰、结构化的回复，避免使用复杂的格式标记。每个建议应简洁明了，避免过多修饰词。提供的内容应直接可用，不需要额外解释。回答需要针对学生的具体情况给出个性化建议。");
      messages.add(systemMessage);

      Map<String, String> userMessage = new HashMap<>();
      userMessage.put("role", "user");
      userMessage.put("content", prompt);
      messages.add(userMessage);

      requestBody.put("messages", messages);
      requestBody.put("temperature", 0.7);
      requestBody.put("max_tokens", 800);

      // 创建HTTP请求实体
      HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

      // 发送请求
      ResponseEntity<String> response = restTemplate.postForEntity(SHISA_AI_API_URL, requestEntity, String.class);

      // 解析响应
      JSONObject responseJson = JSON.parseObject(response.getBody());
      JSONArray choices = responseJson.getJSONArray("choices");

      if (choices != null && !choices.isEmpty()) {
        JSONObject choice = choices.getJSONObject(0);
        JSONObject message = choice.getJSONObject("message");
        return message.getString("content");
      }

      return "AI未能生成有效内容";

    } catch (Exception e) {
      log.error("调用AI API失败", e);
      return "生成内容时出现错误，请稍后再试";
    }
  }

  @Override
  public List<ExamHelperVO> getUserExamHelpers(Integer userId) {
    log.info("获取用户考试助手信息，userId:{}", userId);

    List<ExamHelper> examHelpers = lambdaQuery()
        .eq(ExamHelper::getUserId, userId)
        .eq(ExamHelper::getIsDelete, 0)
        .orderByAsc(ExamHelper::getExamDate)
        .list();

    List<ExamHelperVO> voList = new ArrayList<>();

    for (ExamHelper helper : examHelpers) {
      ExamHelperVO vo = convertToVO(helper);
      voList.add(vo);
    }

    return voList;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public StudyPlanVO createStudyPlan(Integer userId, StudyPlanRequest request) {
    log.info("创建或更新复习计划，userId:{}, courseId:{}", userId, request.getCourseId());

    // 查询是否已存在
    ExamHelper examHelper = lambdaQuery()
        .eq(ExamHelper::getUserId, userId)
        .eq(ExamHelper::getCourseId, request.getCourseId())
        .eq(ExamHelper::getIsDelete, 0)
        .one();

    if (examHelper == null) {
      examHelper = new ExamHelper();
      examHelper.setUserId(userId);
      examHelper.setCourseId(request.getCourseId());
      examHelper.setStudyProgress(0);
      examHelper.setAnxietyLevel(5); // 默认中等焦虑
      examHelper.setCreateTime(new Date());
      examHelper.setIsDelete(0);
    }

    // 更新考试信息
    examHelper.setExamDate(request.getExamDate());
    examHelper.setExamLocation(request.getExamLocation());
    examHelper.setUpdateTime(new Date());

    // 调用AI生成复习计划
    JSONObject studyPlan = generateAiStudyPlan(request);
    examHelper.setStudyPlanJson(studyPlan.toJSONString());

    // 保存或更新
    this.saveOrUpdate(examHelper);

    // 返回VO
    StudyPlanVO vo = new StudyPlanVO();
    vo.setDailySchedule(studyPlan.getJSONObject("dailySchedule"));
    vo.setKeyPoints(studyPlan.getJSONArray("keyPoints").toJavaList(String.class));
    vo.setAiSuggestion(studyPlan.getString("aiSuggestion"));
    vo.setTotalDays(studyPlan.getInteger("totalDays"));
    vo.setCompletedDays(0);

    return vo;
  }

  @Override
  public PredictedPointVO getPredictedPoints(Integer userId, Integer courseId) {
    log.info("获取预测考点，userId:{}, courseId:{}", userId, courseId);

    // 获取考试助手记录
    ExamHelper examHelper = lambdaQuery()
        .eq(ExamHelper::getUserId, userId)
        .eq(ExamHelper::getCourseId, courseId)
        .eq(ExamHelper::getIsDelete, 0)
        .one();

    PredictedPointVO vo = new PredictedPointVO();

    // 已有预测考点则直接返回
    if (examHelper != null && examHelper.getPredictedPoints() != null) {
      try {
        // 修复: 使用TypeReference明确指定泛型类型
        List<Map<String, Object>> predictedPoints = JSON.parseObject(
            examHelper.getPredictedPoints(),
            new TypeReference<List<Map<String, Object>>>() {
            });
        vo.setPredictedPoints(predictedPoints);
        vo.setConfidenceScore(0.85);
        vo.setAiAnalysis("基于历年考题分析和课程重点，以上知识点很可能出现在考试中。");
        return vo;
      } catch (Exception e) {
        log.error("解析预测考点数据失败", e);
      }
    }

    // 调用AI生成预测考点
    List<Map<String, Object>> predictedPoints = generateAiPredictedPoints(courseId);

    // 如果考试助手记录存在，更新预测考点
    if (examHelper != null) {
      examHelper.setPredictedPoints(JSON.toJSONString(predictedPoints));
      examHelper.setUpdateTime(new Date());
      this.updateById(examHelper);
    } else {
      // 创建新的考试助手记录
      ExamHelper newHelper = new ExamHelper();
      newHelper.setUserId(userId);
      newHelper.setCourseId(courseId);
      newHelper.setPredictedPoints(JSON.toJSONString(predictedPoints));
      newHelper.setStudyProgress(0);
      newHelper.setAnxietyLevel(5);
      newHelper.setCreateTime(new Date());
      newHelper.setUpdateTime(new Date());
      newHelper.setIsDelete(0);
      this.save(newHelper);
    }

    // 设置返回结果
    vo.setPredictedPoints(predictedPoints);
    vo.setConfidenceScore(0.85);
    vo.setAiAnalysis("基于历年考题分析和课程重点，以上知识点很可能出现在考试中。");

    return vo;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Boolean addWrongQuestion(Integer userId, WrongQuestionRequest request) {
    log.info("添加错题记录，userId:{}, courseId:{}", userId, request.getCourseId());

    // 获取考试助手记录
    ExamHelper examHelper = lambdaQuery()
        .eq(ExamHelper::getUserId, userId)
        .eq(ExamHelper::getCourseId, request.getCourseId())
        .eq(ExamHelper::getIsDelete, 0)
        .one();

    // 获取或初始化错题集
    List<Map<String, Object>> wrongQuestions = new ArrayList<>();
    if (examHelper != null && examHelper.getWrongQuestions() != null) {
      try {
        // 修复: 使用TypeReference明确指定泛型类型
        wrongQuestions = JSON.parseObject(
            examHelper.getWrongQuestions(),
            new TypeReference<List<Map<String, Object>>>() {
            });
      } catch (Exception e) {
        log.error("解析错题集数据失败", e);
      }
    }

    // 调用AI分析错题
    Map<String, Object> wrongQuestion = analyzeWrongQuestion(request);
    wrongQuestions.add(wrongQuestion);

    // 保存或更新
    if (examHelper == null) {
      examHelper = new ExamHelper();
      examHelper.setUserId(userId);
      examHelper.setCourseId(request.getCourseId());
      examHelper.setStudyProgress(0);
      examHelper.setAnxietyLevel(5);
      examHelper.setCreateTime(new Date());
      examHelper.setIsDelete(0);
    }

    examHelper.setWrongQuestions(JSON.toJSONString(wrongQuestions));
    examHelper.setLastReviewTime(new Date());
    examHelper.setUpdateTime(new Date());

    return this.saveOrUpdate(examHelper);
  }

  @Override
  public AnxietyTipsVO getAnxietyTips(Integer userId, Integer courseId) {
    log.info("获取考前焦虑缓解建议，userId:{}, courseId:{}", userId, courseId);

    // 获取考试助手记录
    ExamHelper examHelper = lambdaQuery()
        .eq(ExamHelper::getUserId, userId)
        .eq(ExamHelper::getCourseId, courseId)
        .eq(ExamHelper::getIsDelete, 0)
        .one();

    // 确定焦虑级别
    Integer anxietyLevel = 5; // 默认中等焦虑
    if (examHelper != null && examHelper.getAnxietyLevel() != null) {
      anxietyLevel = examHelper.getAnxietyLevel();
    }

    // 调用AI生成焦虑缓解建议
    return generateAnxietyTips(anxietyLevel);
  }

  @Override
  public Boolean updateStudyProgress(Integer userId, Integer courseId, Integer progress) {
    log.info("更新学习进度，userId:{}, courseId:{}, progress:{}", userId, courseId, progress);

    // 获取考试助手记录
    ExamHelper examHelper = lambdaQuery()
        .eq(ExamHelper::getUserId, userId)
        .eq(ExamHelper::getCourseId, courseId)
        .eq(ExamHelper::getIsDelete, 0)
        .one();

    if (examHelper == null) {
      log.warn("未找到相关考试信息，userId:{}, courseId:{}", userId, courseId);
      return false;
    }

    // 更新学习进度
    examHelper.setStudyProgress(progress);
    examHelper.setLastReviewTime(new Date());
    examHelper.setUpdateTime(new Date());

    return this.updateById(examHelper);
  }

  /**
   * 将实体转换为VO
   */
  private ExamHelperVO convertToVO(ExamHelper examHelper) {
    ExamHelperVO vo = new ExamHelperVO();
    vo.setId(examHelper.getId());
    vo.setCourseId(examHelper.getCourseId());
    vo.setCourseName("课程" + examHelper.getCourseId()); // 实际项目中应该关联课程表获取
    vo.setExamDate(examHelper.getExamDate());
    vo.setExamLocation(examHelper.getExamLocation());
    vo.setStudyProgress(examHelper.getStudyProgress());
    vo.setAnxietyLevel(examHelper.getAnxietyLevel());

    // 计算剩余天数
    if (examHelper.getExamDate() != null) {
      LocalDate examDate = examHelper.getExamDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
      LocalDate today = LocalDate.now();
      long daysUntil = ChronoUnit.DAYS.between(today, examDate);
      vo.setRemainingDays((int) daysUntil);
    }

    // 解析复习计划JSON
    if (examHelper.getStudyPlanJson() != null) {
      try {
        vo.setStudyPlan(JSON.parseObject(examHelper.getStudyPlanJson()));
      } catch (Exception e) {
        log.error("解析复习计划JSON失败", e);
      }
    }

    // 解析预测考点JSON
    if (examHelper.getPredictedPoints() != null) {
      try {
        // 修复: 使用parseObject而不是parse，指定返回类型
        vo.setPredictedPoints(JSON.parseObject(examHelper.getPredictedPoints()));
      } catch (Exception e) {
        log.error("解析预测考点JSON失败", e);
      }
    }

    return vo;
  }

  /**
   * 调用AI生成复习计划 - 改进解析逻辑
   */
  private JSONObject generateAiStudyPlan(StudyPlanRequest request) {
    JSONObject studyPlan = new JSONObject();

    try {
      // 计算剩余天数
      LocalDate examDate = request.getExamDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
      LocalDate today = LocalDate.now();
      long daysUntilExam = ChronoUnit.DAYS.between(today, examDate);

      if (daysUntilExam <= 0) {
        throw new RuntimeException("考试日期必须在今天之后");
      }

      // 构建更结构化的AI请求
      String prompt = String.format(
          "请你作为学习规划专家，为学生制定一份考试复习计划。请使用以下格式回复：\n\n" +
              "【每日计划】\n" +
              "第1天：[日期]，重点：[重点内容]，任务：[具体任务，用逗号分隔]\n" +
              "第2天：[日期]，重点：[重点内容]，任务：[具体任务，用逗号分隔]\n" +
              "...\n\n" +
              "【重点知识】\n" +
              "1. [知识点1]\n" +
              "2. [知识点2]\n" +
              "...\n\n" +
              "【学习建议】\n" +
              "[一段简短的学习建议]\n\n" +
              "考试科目：课程%d\n" +
              "距离考试还有%d天\n" +
              "每天可用学习时间：%d小时\n" +
              "要求：计划科学合理，循序渐进，包含复习和自测环节，避免赘述。",
          request.getCourseId(), daysUntilExam, request.getDailyStudyHours());

      // 调用AI接口
      String aiResponse = callAiApi(prompt);
      log.info("AI生成复习计划响应: {}", aiResponse);

      // 解析AI响应生成每日计划
      JSONObject dailySchedule = new JSONObject();
      List<String> keyPoints = new ArrayList<>();
      String aiSuggestion = "";

      // 提取每日计划
      Pattern dayPattern = Pattern.compile("第(\\d+)天：.*?重点：(.*?)，任务：(.*?)(?=\n|$)");
      Matcher dayMatcher = dayPattern.matcher(aiResponse);

      while (dayMatcher.find() && dailySchedule.size() < Math.min((int) daysUntilExam, 14)) {
        int dayNum = Integer.parseInt(dayMatcher.group(1));
        String focus = cleanText(dayMatcher.group(2));
        String tasksStr = cleanText(dayMatcher.group(3));

        JSONObject dayPlan = new JSONObject();
        dayPlan.put("focus", focus);

        // 分割任务列表
        List<String> tasks = new ArrayList<>();
        for (String task : tasksStr.split("，|,")) {
          String cleanTask = cleanText(task);
          if (!cleanTask.isEmpty()) {
            tasks.add(cleanTask);
          }
        }

        dayPlan.put("tasks", tasks);
        dayPlan.put("duration", request.getDailyStudyHours() * 60);

        dailySchedule.put("day" + dayNum, dayPlan);
      }

      // 如果无法解析每日计划，则使用简单默认值
      if (dailySchedule.isEmpty()) {
        for (int i = 1; i <= Math.min((int) daysUntilExam, 14); i++) {
          JSONObject dayPlan = new JSONObject();
          dayPlan.put("focus", "第" + i + "天的学习重点");
          dayPlan.put("tasks", Arrays.asList("复习章节内容", "做练习题", "回顾笔记"));
          dayPlan.put("duration", request.getDailyStudyHours() * 60);

          dailySchedule.put("day" + i, dayPlan);
        }
      }

      // 提取重点知识
      Pattern pointPattern = Pattern.compile("【重点知识】\\s*(?:\\n|\\r\\n)((.|\\n)*?)(?=\\n\\s*【|$)");
      Matcher pointMatcher = pointPattern.matcher(aiResponse);
      if (pointMatcher.find()) {
        String pointsSection = pointMatcher.group(1);
        Pattern listItemPattern = Pattern.compile("\\d+\\.\\s*(.+)");
        Matcher listItemMatcher = listItemPattern.matcher(pointsSection);

        while (listItemMatcher.find() && keyPoints.size() < 5) {
          String point = cleanText(listItemMatcher.group(1));
          if (!point.isEmpty()) {
            keyPoints.add(point);
          }
        }
      }

      // 如果无法提取重点知识，使用默认值
      if (keyPoints.isEmpty()) {
        keyPoints.add("课程核心概念");
        keyPoints.add("重要公式和定理");
        keyPoints.add("常见考点和题型");
        keyPoints.add("历年易错点");
        keyPoints.add("课程难点解析");
      }

      // 提取学习建议
      Pattern suggestionPattern = Pattern.compile("【学习建议】\\s*(?:\\n|\\r\\n)((.|\\n)*?)(?=\\n\\s*【|$)");
      Matcher suggestionMatcher = suggestionPattern.matcher(aiResponse);
      if (suggestionMatcher.find()) {
        aiSuggestion = cleanText(suggestionMatcher.group(1));
      } else {
        aiSuggestion = "建议每天保持固定学习时间，注意休息，定期回顾已学内容，多做练习题巩固知识点。";
      }

      // 组装复习计划
      studyPlan.put("dailySchedule", dailySchedule);
      studyPlan.put("keyPoints", keyPoints);
      studyPlan.put("aiSuggestion", aiSuggestion);
      studyPlan.put("totalDays", (int) daysUntilExam);

    } catch (Exception e) {
      log.error("生成复习计划失败", e);
      // 降级方案：返回简单计划
      JSONObject defaultSchedule = new JSONObject();
      JSONObject day1 = new JSONObject();
      day1.put("focus", "基础知识复习");
      day1.put("tasks", Arrays.asList("复习课本第1-3章", "做基础练习题"));
      day1.put("duration", 120);
      defaultSchedule.put("day1", day1);

      studyPlan.put("dailySchedule", defaultSchedule);
      studyPlan.put("keyPoints", Arrays.asList("核心概念", "基本原理", "常见题型"));
      studyPlan.put("aiSuggestion", "请合理安排时间，循序渐进地复习。");
      studyPlan.put("totalDays", 7);
    }

    return studyPlan;
  }

  /**
   * 调用AI生成预测考点 - 改进解析逻辑
   */
  private List<Map<String, Object>> generateAiPredictedPoints(Integer courseId) {
    List<Map<String, Object>> predictedPoints = new ArrayList<>();

    try {
      // 构建结构化的AI提示
      String prompt = String.format(
          "请你作为教育专家，预测课程%d的考试重点。请使用以下格式回复5个重点知识点：\n\n" +
              "知识点1：[名称]\n" +
              "重要性：[0-1之间的数值]\n" +
              "描述：[具体描述]\n" +
              "复习建议：[复习建议]\n\n" +
              "知识点2：[名称]\n" +
              "... (重复相同格式)\n\n" +
              "请确保每个字段内容简明扼要，直接可用。",
          courseId);

      // 调用AI接口
      String aiResponse = callAiApi(prompt);
      log.info("AI生成预测考点响应: {}", aiResponse);

      // 解析AI回复提取考点信息
      Pattern pointPattern = Pattern
          .compile("知识点\\d+：(.*?)\\s*重要性：(\\d+\\.?\\d*)\\s*描述：(.*?)\\s*复习建议：(.*?)(?=\\s*知识点\\d+|$)", Pattern.DOTALL);
      Matcher matcher = pointPattern.matcher(aiResponse);

      while (matcher.find() && predictedPoints.size() < 5) {
        try {
          String title = cleanText(matcher.group(1));
          String probabilityStr = matcher.group(2);
          String description = cleanText(matcher.group(3));
          String reviewTips = cleanText(matcher.group(4));

          double probability = 0.8; // 默认值
          try {
            probability = Double.parseDouble(probabilityStr);
            // 确保概率在0-1之间
            probability = Math.max(0, Math.min(1, probability));
          } catch (NumberFormatException e) {
            log.warn("无法解析重要性评分: {}", probabilityStr);
          }

          Map<String, Object> point = new HashMap<>();
          point.put("title", title);
          point.put("probability", probability);
          point.put("description", description);
          point.put("reviewTips", reviewTips);

          predictedPoints.add(point);
        } catch (Exception e) {
          log.error("解析预测考点时出错", e);
        }
      }

      // 如果无法从AI回复中提取足够的考点，添加一些默认值凑够5个
      while (predictedPoints.size() < 5) {
        Map<String, Object> point = new HashMap<>();
        int index = predictedPoints.size() + 1;
        point.put("title", "预测考点" + index);
        point.put("probability", 0.75 + (index * 0.03));
        point.put("description", "这是预测考点" + index + "的详细描述，涵盖该知识点的核心内容和常见题型。");
        point.put("reviewTips", "建议重点复习相关概念，多做此类练习题，掌握解题技巧。");

        predictedPoints.add(point);
      }

    } catch (Exception e) {
      log.error("生成预测考点失败", e);
      // 降级方案：返回基础考点
      Map<String, Object> defaultPoint = new HashMap<>();
      defaultPoint.put("title", "核心知识点");
      defaultPoint.put("probability", 0.9);
      defaultPoint.put("description", "课程的基础概念和核心原理");
      defaultPoint.put("reviewTips", "重点复习课本内容，理解基本概念");

      predictedPoints.add(defaultPoint);
    }

    return predictedPoints;
  }

  /**
   * 调用AI分析错题 - 增强解析能力
   */
  private Map<String, Object> analyzeWrongQuestion(WrongQuestionRequest request) {
    Map<String, Object> wrongQuestion = new HashMap<>();

    try {
      // 构建结构化的AI提示
      String prompt = String.format(
          "请你作为专业教师，分析以下错题并按照指定格式回复：\n\n" +
              "题目：%s\n" +
              "错误答案：%s\n" +
              "正确答案：%s\n" +
              "知识点：%s\n\n" +
              "请按以下格式回答：\n" +
              "【错误分析】\n" +
              "[详细分析学生的错误原因]\n\n" +
              "【知识点解释】\n" +
              "[相关知识点的关键概念解释]\n\n" +
              "【学习建议】\n" +
              "1. [建议1]\n" +
              "2. [建议2]\n" +
              "3. [建议3]\n\n" +
              "回答要简洁明了，直接可用，避免复杂格式。",
          request.getQuestionContent(),
          request.getWrongAnswer(),
          request.getCorrectAnswer(),
          request.getKnowledgePoint());

      // 调用AI接口
      String aiResponse = callAiApi(prompt);
      log.info("AI分析错题响应: {}", aiResponse);

      // 提取错误分析
      String analysis = extractSection(aiResponse, "【错误分析】", "【知识点解释】");
      if (analysis.isEmpty()) {
        analysis = "学生对该知识点理解不够深入，需要加强此部分内容的学习。";
      }

      // 提取学习建议
      List<String> suggestions = new ArrayList<>();
      Pattern suggestionPattern = Pattern.compile("【学习建议】\\s*(?:\\n|\\r\\n)?((.|\\n)*?)(?=\\n\\s*【|$)");
      Matcher suggestionMatcher = suggestionPattern.matcher(aiResponse);

      if (suggestionMatcher.find()) {
        String suggestionsSection = suggestionMatcher.group(1);
        Pattern listItemPattern = Pattern.compile("\\d+\\.\\s*(.+)");
        Matcher listItemMatcher = listItemPattern.matcher(suggestionsSection);

        while (listItemMatcher.find()) {
          String suggestion = cleanText(listItemMatcher.group(1));
          if (!suggestion.isEmpty()) {
            suggestions.add(suggestion);
          }
        }
      }

      // 如果没有提取到建议，使用默认值
      if (suggestions.isEmpty()) {
        suggestions = Arrays.asList(
            "回顾相关基础概念",
            "做更多相关练习题",
            "理解而不是记忆");
      }

      // 填充错题分析
      wrongQuestion.put("questionContent", request.getQuestionContent());
      wrongQuestion.put("wrongAnswer", request.getWrongAnswer());
      wrongQuestion.put("correctAnswer", request.getCorrectAnswer());
      wrongQuestion.put("knowledgePoint", request.getKnowledgePoint());
      wrongQuestion.put("difficulty", request.getDifficulty());
      wrongQuestion.put("analysis", analysis);
      wrongQuestion.put("suggestions", suggestions);
      wrongQuestion.put("reviewTimes", 0);
      wrongQuestion.put("lastReviewTime", new Date());

    } catch (Exception e) {
      log.error("分析错题失败", e);
      // 降级方案：基本错题记录
      wrongQuestion.put("questionContent", request.getQuestionContent());
      wrongQuestion.put("wrongAnswer", request.getWrongAnswer());
      wrongQuestion.put("correctAnswer", request.getCorrectAnswer());
      wrongQuestion.put("knowledgePoint", request.getKnowledgePoint());
      wrongQuestion.put("difficulty", request.getDifficulty());
      wrongQuestion.put("analysis", "请仔细复习相关知识点。");
      wrongQuestion.put("suggestions", Collections.singletonList("多练习类似题目"));
      wrongQuestion.put("reviewTimes", 0);
      wrongQuestion.put("lastReviewTime", new Date());
    }

    return wrongQuestion;
  }

  /**
   * 调用AI生成焦虑缓解建议 - 更精确的提示和解析
   */
  private AnxietyTipsVO generateAnxietyTips(Integer anxietyLevel) {
    AnxietyTipsVO vo = new AnxietyTipsVO();

    try {
      // 更结构化的AI提示
      String prompt = String.format(
          "请你作为心理咨询师，为焦虑程度为%d（满分10分）的考试学生提供缓解建议。请使用以下格式回复：\n\n" +
              "【放松技巧】\n" +
              "1. [技巧1，简洁描述]\n" +
              "2. [技巧2，简洁描述]\n" +
              "3. [技巧3，简洁描述]\n" +
              "4. [技巧4，简洁描述]\n" +
              "5. [技巧5，简洁描述]\n\n" +
              "【学习建议】\n" +
              "1. [建议1，简洁描述]\n" +
              "2. [建议2，简洁描述]\n" +
              "3. [建议3，简洁描述]\n\n" +
              "【个人建议】\n" +
              "[一段针对性的个人建议，100-150字]\n\n" +
              "【正念练习】\n" +
              "1. [练习1，简洁描述]\n" +
              "2. [练习2，简洁描述]\n" +
              "3. [练习3，简洁描述]\n\n" +
              "请确保回复内容简洁直接，不要使用特殊格式如**加粗**、*斜体*等，避免使用多余的标点符号。",
          anxietyLevel);

      // 调用AI接口
      String aiResponse = callAiApi(prompt);
      log.info("AI生成焦虑缓解建议响应: {}", aiResponse);

      // 解析AI响应
      if (aiResponse != null && !aiResponse.isEmpty()) {
        List<String> relaxationTechniques = extractListItems(aiResponse, "【放松技巧】");
        List<String> studyTips = extractListItems(aiResponse, "【学习建议】");
        String personalizedAdvice = extractSection(aiResponse, "【个人建议】", "【正念练习】");
        List<String> mindfulnessExercises = extractListItems(aiResponse, "【正念练习】");

        // 使用AI提取的内容或默认值
        vo.setRelaxationTechniques(
            relaxationTechniques.isEmpty() ? getDefaultRelaxationTechniques() : relaxationTechniques);

        vo.setStudyTips(studyTips.isEmpty() ? getDefaultStudyTips() : studyTips);

        vo.setPersonalizedAdvice(
            personalizedAdvice.isEmpty() ? getDefaultPersonalizedAdvice(anxietyLevel) : personalizedAdvice);

        vo.setMindfulnessExercises(
            mindfulnessExercises.isEmpty() ? getDefaultMindfulnessExercises() : mindfulnessExercises);

        return vo;
      }

      // 解析失败时使用默认值
      throw new Exception("无法解析AI响应");

    } catch (Exception e) {
      log.error("生成焦虑缓解建议失败", e);
      // 降级方案：返回预设内容
      vo.setRelaxationTechniques(getDefaultRelaxationTechniques());
      vo.setStudyTips(getDefaultStudyTips());
      vo.setPersonalizedAdvice(getDefaultPersonalizedAdvice(anxietyLevel));
      vo.setMindfulnessExercises(getDefaultMindfulnessExercises());
    }

    return vo;
  }

  /**
   * 提取列表项的通用方法
   */
  private List<String> extractListItems(String text, String sectionHeader) {
    List<String> items = new ArrayList<>();

    // 查找章节内容
    Pattern sectionPattern = Pattern
        .compile(Pattern.quote(sectionHeader) + "\\s*(?:\\n|\\r\\n)?((.|\\n)*?)(?=\\n\\s*【|$)");
    Matcher sectionMatcher = sectionPattern.matcher(text);

    if (sectionMatcher.find()) {
      String sectionContent = sectionMatcher.group(1);
      // 匹配编号列表项
      Pattern listItemPattern = Pattern.compile("\\d+\\.\\s*(.+)");
      Matcher listItemMatcher = listItemPattern.matcher(sectionContent);

      while (listItemMatcher.find()) {
        String item = cleanText(listItemMatcher.group(1));
        if (!item.isEmpty()) {
          items.add(item);
        }
      }
    }

    return items;
  }

  /**
   * 提取章节内容的通用方法
   */
  private String extractSection(String text, String startMarker, String endMarker) {
    int startIndex = text.indexOf(startMarker);
    if (startIndex < 0)
      return "";

    startIndex += startMarker.length();
    int endIndex = text.indexOf(endMarker, startIndex);
    if (endIndex < 0)
      endIndex = text.length();

    String section = text.substring(startIndex, endIndex).trim();
    return cleanText(section);
  }

  /**
   * 完善提取学习建议的方法
   */
  private List<String> extractStudyTips(String aiResponse) {
    return extractListItems(aiResponse, "【学习建议】");
  }

  /**
   * 完善提取个人建议的方法
   */
  private String extractPersonalizedAdvice(String aiResponse) {
    return extractSection(aiResponse, "【个人建议】", "【正念练习】");
  }

  /**
   * 完善提取正念练习的方法
   */
  private List<String> extractMindfulnessExercises(String aiResponse) {
    return extractListItems(aiResponse, "【正念练习】");
  }

  // 清理文本，移除Markdown标记和多余空白
  private String cleanText(String text) {
    // 移除Markdown标记
    String cleaned = text.replaceAll("\\*\\*|\\*|`|#+\\s?", "");
    // 移除项目符号
    cleaned = cleaned.replaceAll("^[-•]\\s*", "");
    // 移除作用、步骤等说明前缀
    cleaned = cleaned.replaceAll("^(作用|步骤|方法)[:：]\\s*", "");
    // 移除多余空白
    cleaned = cleaned.trim();
    return cleaned;
  }

  // 默认值方法，作为降级方案
  private List<String> getDefaultRelaxationTechniques() {
    return Arrays.asList(
        "深呼吸练习：慢慢吸气数到4，屏住呼吸数到4，然后缓慢呼气数到6",
        "渐进性肌肉放松：有意识地紧绷然后放松身体各个部位的肌肉",
        "5-4-3-2-1感官练习：专注于5个你能看到的东西，4个你能触摸到的东西，3个你能听到的声音，2个你能闻到的气味和1个你能尝到的味道",
        "冥想：每天花10分钟进行专注呼吸的冥想",
        "轻度运动：散步、伸展运动或瑜伽等轻度运动有助于缓解身体紧张");
  }

  private List<String> getDefaultStudyTips() {
    return Arrays.asList(
        "番茄工作法：专注学习25分钟，休息5分钟",
        "主动回忆：阅读内容后，合上书本，尝试回忆关键点",
        "分散学习：每天学习一点比集中在一天内学习更有效");
  }

  private String getDefaultPersonalizedAdvice(Integer anxietyLevel) {
    if (anxietyLevel >= 8) {
      return "你的焦虑程度较高，建议先专注于放松技巧，降低整体焦虑水平。记住，考试只是检验学习成果的一种方式，不能定义你的整体价值。";
    } else if (anxietyLevel >= 5) {
      return "记住，考试只是检验学习成果的一种方式，不能定义你的整体价值。保持充足的睡眠，均衡的饮食，适当的运动，这些都能帮助你保持良好的状态。相信自己的准备，专注于过程而非结果。";
    } else {
      return "你的焦虑程度相对较低，这是一个好的状态。保持这种平和的心态，合理安排学习时间，相信自己的能力。";
    }
  }

  private List<String> getDefaultMindfulnessExercises() {
    return Arrays.asList(
        "专注呼吸：专注于自己的呼吸，观察每一次吸气和呼气",
        "身体扫描：从头到脚，依次关注身体各部位的感觉",
        "正念行走：走路时专注于脚部与地面接触的感觉");
  }
}